import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:get/get.dart';
import 'dart:collection';
import '../../models/common/Settings.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/controller/cache.dart';

var notext = 'No Text';

enum TextOptions { Simplified, Traditional, notext }

enum AudioOptions { Mandarin, Cantonese, No_audio }

enum AutoplayOptions { True, False }

enum PinyinOptions { True, False }

TextOptions? text;
AudioOptions? audio;
AutoplayOptions? auto;
PinyinOptions? pinyinS;

//使用webview的方式打开书；此插件只支持apps，桌面版和web版暂不支持
class InAppWebViewAppMiniBookScreen extends StatefulWidget {
  const InAppWebViewAppMiniBookScreen({
    Key? key,
    this.bookId,
    this.bookCode,
    this.bookTitle,
    this.lang,
    this.language,
    this.assignmentId,
  }) : super(key: key);
  final String? bookId;
  final String? bookCode;
  final String? bookTitle;
  final String? lang;
  final String? language;
  final String? assignmentId;

  static const String routeName = '/student/minibook';

  @override
  _InAppWebViewAppMiniBookScreenState createState() =>
      new _InAppWebViewAppMiniBookScreenState();
}

var globalController;
var iFrame;
final box = Hive.box('appconfig');

class _InAppWebViewAppMiniBookScreenState
    extends State<InAppWebViewAppMiniBookScreen> {
  final GlobalKey webViewKey = GlobalKey();
  InAppWebViewController? webViewController;
  InAppWebViewSettings options = InAppWebViewSettings(
      useShouldOverrideUrlLoading: true,
      mediaPlaybackRequiresUserGesture: false,
      useHybridComposition: true,
      allowsInlineMediaPlayback: true,
      allowFileAccessFromFileURLs: true,
      allowUniversalAccessFromFileURLs: true,
      cacheEnabled: true,
      domStorageEnabled: true,
      javaScriptEnabled: true,
      allowsPictureInPictureMediaPlayback: true,
      enableViewportScale: true,
      disableLongPressContextMenuOnLinks: true,
      // requestedWithHeaderMode: RequestedWithHeaderMode.APP_PACKAGE_NAME,
      // iframeAllow: "camera; microphone",
      // iframeAllowFullscreen: true,
      mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW);

  late PullToRefreshController pullToRefreshController;
  late ContextMenu contextMenu;
  var textDisplay, textToggle = true, voices, dictionary, music, noAudio;
  String url = '';
  //String _authtoken = '';
  String _lang = '';
  String _language = '';
  bool _pinyin = false;
  String _bookBasePath = '';
  String _bookCode = '';
  double ratio = 1;

  double progress = 0;
  final urlController = TextEditingController();

  CookieManager cookieManager = CookieManager.instance();
  final BooksController _booksController = Get.find();
  final box = Hive.box('appconfig');
  final expiresDate =
      DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;

  @override
  void initState() {
    super.initState();
    pullToRefreshController = PullToRefreshController(
      // options: PullToRefreshOptions(
      //   color: Colors.blue,
      // ),
      onRefresh: () async {
        if (GetPlatform.isAndroid) {
          webViewController?.reload();
        } else if (GetPlatform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
    _lang = widget.lang ?? '';
    _language = widget.language ?? 'Simplified';
    _bookCode = widget.bookCode ?? 'Mandarin';
    _bookBasePath =
        'https://resources.ichinesereader.com/books/$_bookCode/assets';
  }

  @override
  void dispose() {
    super.dispose();
  }

  String settingsToJson(Settings? data) => json.encode(data!.toJson());

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    // double width = 2000;
    // double height = 1500;
    var hr, wr;
    var viewMode = box.get(CacheManagerKey['_viewMode'].toString());
    if (viewMode == 'LANDSCAPE') {
      hr = (height - AppBar().preferredSize.height) / 728;
      wr = width / 1024;
      if (hr < wr) {
        ratio = hr;
      } else {
        ratio = wr;
      }
    } else {
      // avoid to cut bottom text
      //hr = (height - AppBar().preferredSize.height - 40) / 984;
      hr = (height - AppBar().preferredSize.height - 200) / 984;
      ratio = hr;
    }
    //print(ratio);
    if (ratio > 1.10) {
      ratio = 1.10;
    }

    if (_language == 'Simplified') {
      textDisplay = 's';
    } else if (_language == 'Traditional') {
      textDisplay = 't';
    } else {
      textToggle = false;
    }
    if (_lang == 'Mandarin' || _lang == 'Cantonese') {
      voices = true;
    } else {
      voices = false;
    }
    noAudio = _lang == "No_audio";
    music = voices;
    _pinyin = box.get('UserPinyin') ?? true;
    if (widget.assignmentId != null && widget.assignmentId != '') {
      var assignmentSettings = _booksController.getCurrentAssignmentSettings();
      if (assignmentSettings != null) {
        _pinyin = assignmentSettings.pinyin!;
      }
    }
    dictionary = true;
    var myUserScripts;
    myUserScripts = [
      UserScript(
          source:
              "window.localStorage.setItem('bookBasePath','$_bookBasePath');",
          injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
      // for content
      UserScript(
          source:
              """document.getElementsByTagName('html')[0].style.maxWidth='initial';
                document.getElementsByTagName('html')[0].style.width='auto';
                document.getElementsByTagName('body')[0].style.width='auto';
                document.getElementsByTagName('body')[0].style.transform='scale($ratio)'
                document.getElementsByTagName('body')[0].style.transformOrigin='top center';
                """,
          injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),
      UserScript(
          source:
              """document.getElementById('play-start').style.backgroundImage="url('https://ichinesereader.com/icr/static/media/play_button.2d9092f6.png')";""",
          injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),
      UserScript(source: """window.updatePage = function (page, total) {
                  if(page == total){
                    console.log(true)}
                  }
                  """, injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),
    ];
    return Scaffold(
      //drawer: BookAppDrawer(),
      resizeToAvoidBottomInset: true,
      body: SafeArea(
          child: Column(children: <Widget>[
        Expanded(
          child: Stack(
            children: [
              InAppWebView(
                key: webViewKey,
                initialUrlRequest: URLRequest(
                  url: WebUri(
                      'https://resources.ichinesereader.com/books/$_bookCode/content.html'),
                  //headers: {'authtoken': _authtoken}
                ),
                initialUserScripts:
                    UnmodifiableListView<UserScript>(myUserScripts),
                initialSettings: options,
                pullToRefreshController: pullToRefreshController,
                onLoadStart: (controller, url) async {},
                onPermissionRequest: (controller, request) async {
                  return PermissionResponse(
                      resources: request.resources,
                      action: PermissionResponseAction.GRANT);
                },
                shouldOverrideUrlLoading: (controller, navigationAction) async {
                  var uri = navigationAction.request.url!;

                  if (![
                    "http",
                    "https",
                    "file",
                    "chrome",
                    "data",
                    "javascript",
                    "about"
                  ].contains(uri.scheme)) {
                    if (await canLaunchUrl(uri)) {
                      // Launch the App
                      await launchUrl(
                        uri,
                      );
                      // and cancel the request
                      return NavigationActionPolicy.CANCEL;
                    }
                  }
                  return NavigationActionPolicy.ALLOW;
                },
                onLoadStop: (controller, url) async {
                  Log.debug('****____ONSTOP mini_______*********');
                  pullToRefreshController.endRefreshing();
                  Future.delayed(const Duration(milliseconds: 500), () async {
                    await controller.evaluateJavascript(source: """
                            if($noAudio){
                              readOff();
                              bgmOff();
                            }else{
                              readOn();
                              bgmOn();
                              fLangToggle('${_lang[0].toLowerCase()}');
                            }
                            init(
                              '${widget.bookTitle}',
                              '${widget.bookTitle}',
                              $music,
                              $voices,
                              false,
                              '$textToggle',
                              '$textDisplay',
                              $_pinyin,
                              $dictionary,
                              '${box.get(CacheManagerKey['nanhairole'].toString())}'
                            );
                            """);
                  });
                },
                onReceivedError: (controller, request, error) {
                  pullToRefreshController.endRefreshing();
                },
                onProgressChanged: (controller, progress) {
                  if (progress == 100) {
                    pullToRefreshController.endRefreshing();
                  }
                  setState(() {
                    this.progress = progress / 100;
                    urlController.text = this.url;
                  });
                },
                onUpdateVisitedHistory: (controller, url, androidIsReload) {
                  setState(() {
                    this.url = url.toString();
                    urlController.text = this.url;
                  });
                },
                onConsoleMessage: (controller, consoleMessage) async {
                  Log.debug(consoleMessage);
                },
              ),
              progress < 1.0
                  ? LinearProgressIndicator(value: progress)
                  : Container(),
            ],
          ),
        ),
      ])),
    );
  }
}
